<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>案例-头像上传</title>
    <link rel="stylesheet" href="./bootstrap-v4.6.0.css" />
    <style>
      .thumb-box {
        text-align: center;
        margin-top: 50px;
      }
      .thumb {
        width: 150px;
        height: 150px;
        object-fit: cover;
        border-radius: 50%;
      }
    </style>
  </head>
  <body>
    <div class="thumb-box">
      <img src="./cover.jpg" class="img-thumbnail thumb" alt="" />
      <div class="mt-2">
        <input
          type="file"
          id="iptFile"
          accept="image/*"
          style="display: none"
        />
        <button class="btn btn-primary" id="btnChoose">选择 & 上传图片</button>
      </div>
    </div>
    <script src="./axios.js"></script>
    <script>
      const img = document.querySelector('.thumb')
      const file = document.querySelector('#iptFile')
      const btn = document.querySelector('#btnChoose')
      btn.addEventListener('click', function () {
        file.click()
      })
      file.addEventListener('change', function () {
        if (!file.files[0]) return
        const fn = new FormData()
        fn.append('avatar', file.files[0])
        axios({
          url: 'http://ajax-api.itheima.net/api/file',
          method: 'POST',
          data: fn,
        }).then(({ data: res }) => {
          const ur = res.data.url
          img.src = ur
        })
      })
    </script>
  </body>
</html>
